package multithreading;

import java.util.Random;

public class Demo4_SailTicketsByRunnable_noShare {

    public static void main(String[] args) {

        //创建了三个线程类的对象，目的就是每个对象独占一个线程资源
        Runnable tic_bj = new Tickets("北京");
        Runnable tic_sh = new Tickets("上海");
        Runnable tic_hrb = new Tickets("哈尔滨");

        //Runnable类型只有一个run方法，无法启动线程
        //所以必须借助Thread类中的构造方法 Thread(Runnable target)
        Thread thread_bj = new Thread(tic_bj);
        Thread thread_sh = new Thread(tic_sh);
        Thread thread_hrb = new Thread(tic_hrb);

        thread_bj.start();
        thread_sh.start();
        thread_hrb.start();


        //创建线程的简便方法
//        new Thread(new Tickets("南京")).start();
//
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//
//            }
//        }).start();

    }

}


/**
 * 自定义一个非共享资源卖票的线程类
 */
class Tickets implements Runnable{

    int ticketsCount = 100;
    String stationName = "";

    Random rand = new Random();

    public Tickets(String stationName){
        this.stationName = stationName;
    }

    @Override
    public void run() {
        try{
            for (int i = ticketsCount; i > 0 ; i--) {
                //控制车票的数量
                ticketsCount--;

                System.out.println(this.stationName+"卖了一张车票，剩余："+ticketsCount+"张火车票");

                Thread.sleep(rand.nextInt(500));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}